package top.mcwebsite.playandroid.lib.mvi.base

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

internal fun <T: Any?> Flow<T>.collectLatest(
    lifecycleOwner: LifecycleOwner,
    action: suspend (T) -> Unit
): Job {
    val flow = flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
    val scope = lifecycleOwner.lifecycleScope
    return scope.launch {
        flow.collectLatest(action)
    }
}